package com.wswy.wzcx.module;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import com.che.libcommon.db.SimpleDBHelper;
import com.che.libcommon.utils.CollectionUtils;
import com.che.libcommon.utils.optional.function.Supplier;
import com.wswy.wzcx.model.AreaEntity;
import java.util.ArrayList;
import java.util.List;

public  class DBCity extends SimpleDBHelper {

  private static final String DB_NAME = "wzcx_city";

  private static final String DB_TABLE = "tb_area";

  private static final String[] columns ={"id","name","parent_id","level"};

  public DBCity(Context context) throws SQLiteException {
    super(context, DB_NAME);
    init();
  }

  @Override
  protected String getAssetFile() {
    return "db/wzcx_city.db";
  }


  public List<AreaEntity> getProvinces(){
    return query(new Supplier<Cursor>() {
      @Override
      public Cursor get() {
        return sqLiteDatabase.query(DB_TABLE, columns, "parent_id=?",new String[]{"0"}, null, null,null);

      }
    });
  }

  public List<AreaEntity> getCities(final int provinceId){
    return query(new Supplier<Cursor>() {
      @Override
      public Cursor get() {
        return sqLiteDatabase.query(DB_TABLE, columns, "parent_id=?",new String[]{String.valueOf(provinceId)}, null, null,null);
      }
    });
  }

  public AreaEntity findByName(final String city){
    List<AreaEntity> query = query(new Supplier<Cursor>() {
      @Override
      public Cursor get() {
        return sqLiteDatabase
            .query(DB_TABLE, columns, "name like ? and level = ?", new String[]{"%"+city+"%","2"}, null,
                null, null);
      }
    });
    if(!CollectionUtils.isEmpty(query)){
      return query.get(0);
    }
    return null;
  }

  private List<AreaEntity> query(Supplier<Cursor> supplier){
    Cursor cursor = null;
    try{
      cursor = supplier.get();
      if(cursor != null){
        List<AreaEntity> areaEntities = new ArrayList<>();
        while (cursor.moveToNext()){
          areaEntities.add(mapEntity(cursor));
        }
        return areaEntities;
      }
    }catch (Exception e){
      e.printStackTrace();
    }finally {
      closeCursor(cursor);
    }
    return null;
  }





  private AreaEntity mapEntity(Cursor cursor){
    AreaEntity entity = new AreaEntity();

    entity.id = cursor.getInt(0);
    entity.name = cursor.getString(1);
    entity.parentId = cursor.getInt(2);
    entity.level = cursor.getInt(3);

    return entity;
  }

}
